import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { ZsyzTokenService } from './zsyz-token.service';

@Injectable()
export class ZsyzTokenGuard implements CanActivate {
    constructor(private readonly zsyzTokenService: ZsyzTokenService) { }

    canActivate(context: ExecutionContext): boolean {
        const request = context.switchToHttp().getRequest();
        const token = this.extractTokenFromHeader(request);

        if (!token) {
            throw new UnauthorizedException('未提供认证令牌');
        }

        if (!this.zsyzTokenService.verifyToken(token)) {
            throw new UnauthorizedException('无效的认证令牌');
        }

        const user = this.zsyzTokenService.getUserFromToken(token);
        if (!user) {
            throw new UnauthorizedException('无效的用户信息');
        }

        // 将用户信息添加到请求对象中
        request.user = user;
        return true;
    }

    private extractTokenFromHeader(request: any): string | undefined {
        const [type, token] = request.headers.authorization?.split(' ') ?? [];
        return type === 'Bearer' ? token : undefined;
    }
} 